<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="cn.edu.nju.ws.sview.Config,java.util.Enumeration,cn.edu.nju.ws.sview.views.*,cn.edu.nju.ws.sview.views.data.*,cn.edu.nju.ws.sview.cache.*" %>
<%@page import="cn.edu.nju.ws.sview.util.URIUtil,java.net.URLEncoder,cn.edu.nju.ws.sview.reasoning.schema.InnerClass,cn.edu.nju.ws.sview.util.URIUtil,cn.edu.nju.ws.sview.reasoning.schema.Subclass,cn.edu.nju.ws.sview.rdf.*,cn.edu.nju.ws.sview.crawler.Crawler,cn.edu.nju.ws.sview.crawler.Element" %>
<%@page import="cn.edu.nju.ws.sview.views.Group,java.util.Map.Entry,java.util.ArrayList,java.util.HashSet,java.util.HashMap,cn.edu.nju.ws.sview.database.DBOperations" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SView collection views</title>
<link rel="icon" href="/sview/favicon.ico" />
<link rel="stylesheet" type="text/css" href="/sview/css/layout.css" />
<link rel="stylesheet" type="text/css" href="/sview/css/smoothness/jquery-ui-1.8.16.custom.css" />
<link rel="stylesheet" type="text/css" href="/sview/css/views/bootstrap_nav.min.css" />
<link rel="stylesheet" type="text/css" href="/sview/css/flexigrid.css" />
<link rel="stylesheet" type="text/css" href="/sview/css/views/cview.css" />
<link rel="stylesheet" type="text/css" href="/sview/css/easyui.css" />
<script type="text/javascript" src="/sview/script/jquery.js"></script>
<script type="text/javascript" src="/sview/script/bootstrap.min.js"></script>
<script type="text/javascript" src="/sview/script/jquery.easyui.min.js"></script>
<script type="text/javascript" src="/sview/script/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="/sview/script/jcarousellite_1.0.1.js"></script>
<script type="text/javascript" src="/sview/script/global.js"></script>
<script type="text/javascript" src="/sview/script/views/cview.js"></script>
<script type="text/javascript" src="/sview/script/flexigrid.js"></script>
<script type="text/javascript" src="/sview/script/jquery.jstree.js"></script>
</head>
<body>
<%
	String lang = request.getParameter("lang");
	if(lang!=null &&lang.equals("zh")){
		request.getRequestDispatcher("cview_zh.jsp").forward(request,response);
		return;
	}else if(lang==null){
		lang="en" ;
	}
	String idStr = request.getParameter("id");
	String genre = null;
	int entityId =0;
	if(idStr==null){
		String location = "../views/index.jsp";
		if(lang.equals("zh"))
	location = location+"?lang="+lang;
		response.sendRedirect(location);
		return;
	}else{
		genre = idStr.substring(0,1);
		entityId = Integer.parseInt(idStr.substring(1));
		if(!Entity.isThere(entityId)){
	String location = "../views/eerror.jsp";
	if(lang.equals("zh"))
		location = location+"?lang="+lang;
	response.sendRedirect(location);
	return;
		}
	}
	String user = (String)session.getAttribute("user"); 
	int etype = 0;
    if(genre.equals(Entity.COLLECTION_Str)){
	   	etype = Entity.COLLECTION;
  	}else if(genre.equals(Entity.CUSTOM_ENTITY_Str)) {
	  	etype = Entity.CUSTOM_ENTITY;
   	}else if(genre.equals(Entity.URI_ENTITY_Str))
   		etype = Entity.URI_ENTITY;
    
    String groupName = (String)session.getAttribute("groupName");
    int groupID = 0;
    groupID = Group.getGroupIdByName(groupName);
    
    String name= null;  
    if(genre.equals(Entity.COLLECTION_Str)){
    	name = Entity.getNameByEntityID(entityId,"en");
    }else{
    	String location = "../views/eerror.jsp";
		if(lang.equals("zh"))
	location = location+"?lang="+lang;
		response.sendRedirect(location);
		return;
    }
    if(name==null||name.trim().equals("")){
    	if(lang.equals("en")){
    		name ="untitled";
    	}else if(lang.equals("zh")){
    		name ="未命名";
    	}
    }
    boolean isTmpCollection = Entity.isTmpCollection(Entity.COLLECTION,entityId);
    
    ArrayList<Integer> members = new ArrayList<Integer>(Entity.getMembersByEntityId(entityId));
%>

<%
	/*store entity visit log*/    
    int entityType = -1;   
    if(genre.equals(Entity.COLLECTION_Str))
    	entityType=Entity.COLLECTION;
    else if(genre.equals(Entity.URI_ENTITY_Str))
    	entityType =Entity.URI_ENTITY; 
    else  if(genre.equals(Entity.CUSTOM_ENTITY_Str))
    	entityType = Entity.CUSTOM_ENTITY;
%>

<script type="text/javascript">
     var loaddiv = $("<div class='load-data'></div>");
     $('body').append(loaddiv) ;
</script>
<%
	/*prepare all the related rdf documents*/
    HashSet<Integer> uris = EntityBrowsing.getEntityRelevantURIs(entityType, entityId);
    ArrayList<URIResource> array = new ArrayList<URIResource>();
    for(Integer mid :uris){
    	try{
    		URIResource r = ResourceFactory.getInstance().createURIResource(URIIDCache.getInstance().getURI(mid));
    		if(DBOperations.getValidStatus(mid)!=URIResource.VALID&&Crawler.getInstance().checkStatus(r)==Crawler.STATUS_UNSUBMITTED){
    			Crawler.getInstance().submitURI(r);
    			Crawler.getInstance().promoteWeight(r,Element.LEVEL_1);
    			array.add(r);
    		}
    	}catch(Throwable e){
    		e.printStackTrace();
    	}
    }
    boolean waitflag = true;
    while(waitflag){
    	waitflag =false;
    	 for(URIResource resource:array){
    	     int status = Crawler.getInstance().checkStatus(resource) ;
    	     if(status!=Crawler.STATUS_DONE){
    	    	 waitflag = true;
    	    	 break;
    	     }
    	 }
    	 Thread.sleep(20);
    }
    for(Integer mid :uris){
    	String status = DBOperations.getSuccessStatus(mid);
		if(!status.equals(URIResource.VALID_SUCCEED)){
	/* start:由于DBpedia等网站会被封掉，因此使用falcons数据集作为后备*/
	try{
		      EntityBrowsing.getReserveRDFDescription(URIIDCache.getInstance().getURI(mid));
	}catch(Throwable e){
		e.printStackTrace();
	}
		    /* end:由于DBpedia等网站会被封掉，因此使用falcons数据集作为后备*/   
		}
    }
%>
<script>
   $(".load-data").remove();
</script>
<jsp:include page="/vheader.jsp" flush="true">
   <jsp:param name="f" value="e"/>
</jsp:include>
<div class="container">
 <div class='main-container'>
  <div class="generalInfo">
   <div  class="general_info">
      <div class="general-info-title">
	   <div class="titlename relative">
	   	 <%
	   	 	if(name!=null&&!name.trim().equals("")){
	   	 %> 
	   		<span class="entity-label" genre=<%=genre%> eid=<%=entityId%>><%=name%></span>
	   	  <%
	   	  	}
	   	  %>
	   		  <span class="entity_op">
	   		  	<%
	   		  		if(user!=null&&!isTmpCollection){
	   		  	%>
	   			<a  href="javascript:void(0)"  class="easyui-linkbutton bookmark_op" iconCls="icon-bookmark" plain="true" title="Bookmark this collection">Bookmark</a>
	   			<%
	   				}
	   			%>
                <%
                	int entityGroupID = 0;
                                                  entityGroupID= Entity.getGroupIDOfEntity(entityId);
                                                  if(user!=null&&groupName!=null){
                                                	  if(groupID==entityGroupID){
                %>
	   				<a  href="javascript:void(0)"  class="easyui-menubutton custom_op" iconCls="icon-identity" plain="true" >Customize</a>
	   		 <div class="dmenu" id="emenu">
	   			 <ol>
        			<li><a href="javascript:void(0)" class="entity_edit" title = "Edit this collection">Edit</a></li>
     			 </ol>
     		  </div>
	   		    <%
	   		    	} else if(isTmpCollection){
	   		    %>
	   		       <a  href="javascript:void(0)"  class="easyui-menubutton custom_op" iconCls="icon-identity" plain="true">Customization</a>
	   		   <div class="dmenu" id="emenu">
	   				<ol>
        				<li><a href="javascript:void(0)" class="entity_new" title="Create a new collection">Create</a></li>
     				</ol>
     			</div>
	   		    <%
	   		    	}}
	   		    %>	
	   		  </span> 
	   </div>
	  <%
	  	HashMap<Integer,String> typeMap = new HashMap<Integer,String>();
	  	  	  	    ArrayList<Entry<Integer,String>> typeInfo =null;
	  	  	  	    typeInfo = Entity.getClassTypesById(entityId,lang);
	  	  	  	    for(int i =0;i<typeInfo.size();i++){
	  	  	  	    	Entry<Integer,String> item = typeInfo.get(i);
	  	  	  	    	typeMap.put(item.getKey(),item.getValue());
	  	  	  	    }
	  %>
      </div>
      <div class="meta-info">
         <div class="img-comm">
           <div class="commentBox">
                 <%
                 	int memberNum = uris.size();
                 %>
                 <div class="entity-memnum">
                 	has 
                 	<span class="memnumBox">
                 	   <span class="memnum current"><%=memberNum %></span> member(s)
                 	</span>
                 	<span class="isFilter"> filtered from origin <span class="memnum"><%=memberNum %></span></span>
                 </div>
                 <%
                 	if(typeMap.keySet().size()>0){
                 %>
                  <div class="entity-type">
                 a collection of <span class="type" >
                 <%
                 	int c = 0;  
                                                     for(Integer type_id:typeMap.keySet()){
                                                  	   c++;
                                                  	   if(c>=11){
                 %>
                 <span>...</span> 
                 <%
                  	break;
                                                    	   }
                                                    	   String type_label = typeMap.get(type_id) ;
                                                    	   if(type_label!=null&&!type_label.trim().equals("")){
                  %>
                 <span type_id=<%=type_id%>><%=type_label%></span>
                 <%
                 	}else{
                                                  	     if(!lang.equals("en")){
                                              		   	   try{
                                              		   	     type_label = URILabelCache.getInstance().getLabel(new Integer(type_id),"en");
                                              		   		 if(type_label.equals(""))
                                              		   		   type_label = URIUtil.getLocalname(URIIDCache.getInstance().getURI(type_id)) ;
                                              		   	   }catch(Throwable e){
                                              		   		   e.printStackTrace();
                                              		   	   }
                                              		   	 }
                                                  	     if(type_label.equals("")){
                                             	 	   		   if(lang.equals("en"))
                                             	 	   		     type_label ="Type"+type_id;
                                             	 	   		 else if(lang.equals("zh"))
                                             	 	   			type_label="类型"+type_id;
                                             	 	   	     }
                 %>
                 <span class="vacant" type_id=<%=type_id%>><%=type_label%></span>  
                 <%
                   	}
                                                      	   if(c<typeMap.keySet().size()){
                   %>
                 ,
                 <%
                   	}
                                                         }
                   %>
                 </span>
                   </div>
                 <%
                 	}
                 %>
	           <%
	           	String comment = null;
	           	            	           		      		if(genre.equals(Entity.URI_ENTITY_Str)){
	           	            	           		    			try{
	           	            	           		    	   			String uri = URIIDCache.getInstance().getURI(entityId) ;
	           	            	           		    	   			comment  = Comment.getOriginComment(uri,lang) ;
	           	            	           		    	 		}catch(Throwable e){
	           	            	           		    		 		e.printStackTrace();
	           	            	           		    	 		}
	           	            	           		      		 }else{
	           	            	           		         		String uri = null;
	           	            	           		         	    Comment commObj =  Comment.getCommentByMemberLangGroup(etype,entityId,lang,null);
	           	            	           		         		if(commObj!=null){
	           	            	           		         		 	comment = commObj.getText();
	           	            	           		         		}
	           	            	           		      		 }
	           %> 
 	           <%
  	           	if(comment!=null&&!comment.trim().equals("")){
  	           %>
	              <div  class="comment-box"><label>Description: </label><%=comment%></div>
			   <%
			   	}
			   %>
               <%
               	if(!isTmpCollection){
                                 	        	   int enitytGroupID= Entity.getGroupIDOfEntity(entityId);
                                 	        	   String groupLink = "/sview/group/gprofile.jsp?gid="+enitytGroupID;
                                 	        	   String entityGroupName = Group.getGroupNameById(entityGroupID);
                                 	        	   if(user!=null){
                                 	        	     groupLink = groupLink +"&uname="+user;
                                 	        	   }
                                 	        	   String updateTime = Entity.getLatestUpdateTime(entityId);
               %>
               <div class="entity-group">
	             <span class="ceginfo">Editing group: <a href=<%=groupLink%> target="_blank"><%=entityGroupName%></a></span>
	             <span class="updateinfo">Latest update: <label><%=updateTime%></label></span>
	           </div>
	           <%
	           	}
	           %> 			   
             </div>
         </div>  
	  </div>
	</div>
  </div>
  <div class="main">
  	<div class="relative">
	<%
		HashSet<Integer> minTypes = new HashSet<Integer>();
			   for(Integer tid:typeMap.keySet())
		   minTypes.add(tid) ;
			   try{
			minTypes = Subclass.getInstance().getMinClasses(minTypes);
		}catch(Throwable e){
			e.printStackTrace();
		}
		
		int viewClassID = -1;
		int isInner = 0;
		if(minTypes.size()==1){
			for(Integer mcid:minTypes){
		viewClassID = mcid;
			}
		}else if(minTypes.size()>1){
			viewClassID = InnerClass.getInnerClassID(minTypes,true) ;
			isInner = 1;
		}
	%>
	<div id="minTypes" class="hidden" cid=<%=viewClassID%> inner=<%=isInner%>></div>
	</div>
      <ul class="nav nav-tabs mytab" >
         <li class="members active"><a href="#member-content" >Members</a></li>
         <li class="views"><a href="#view-content" >Views</a></li>
      </ul>
      <div class="tab-content">
        <div class="tab-pane active" id="member-content">
             <div class="memberBox">
              <ul class="memberList">
             <%
             	//need to be checked:merge 
                                          for(Integer uriID:uris){
                                              String memEtype = Entity.URI_ENTITY_Str;
                                              int memEid = uriID;
                                          	String memname = "";
                                          	try{
                                          		memname = URILabelCache.getInstance().getLabel(new Integer(uriID),lang);
                                        	  	    if(memname.equals(""))
                                        	  			memname = URIUtil.getLocalname(URIIDCache.getInstance().getURI(uriID)) ;
                                        	    }catch(Throwable e){
                                        		  e.printStackTrace();
                                        	    }
                                          	HashMap<Integer,String> memTypeMap = new HashMap<Integer,String>();
                                   	  	    try{
                           	  	    		  HashSet<Integer> typeArray = URITypeCache.getInstance().getTypes(uriID) ;
                           	  		    	  int count = 0;
                           	  	    		  for(Integer typeID:typeArray){
                           	  	    			count++;
                           	  		    		String label = URILabelCache.getInstance().getLabel(typeID,lang) ;
                           	  		    		if(label.equals("")&&lang.equals("en")){
                           							String uri = URIIDCache.getInstance().getURI(typeID) ;
                           							label = URIUtil.getLocalname(uri) ;
                           	  		    		}
                           	  		    		memTypeMap.put(typeID,label);
                           	  		    	  }
                           	  	    	    }catch(Throwable e){
                           	  	    		   e.printStackTrace();
                           	  	    	    }
                           	  	    	    ArrayList<String> memImgPath = new ArrayList<String>();
                           	  	    	    try{
                           	    	   		   String uri = URIIDCache.getInstance().getURI(uriID) ;
                           	    	  		   String img_path  = Image.getOriginImage(uri);
                           	    	  		   if(!img_path.trim().equals(""))
                           	    	  			memImgPath.add(img_path);
                           	    	 	     }catch(Throwable e){
                           	    		 	     e.printStackTrace();
                           	    	 	     }
             %>
                 <li etype="<%=memEtype %>" eid="<%=memEid%>">
                     <div class="img-comm">
                     	 <div  class="imgBox">
                     	    <%if(memImgPath.size()>0){ %>
           					<div class="carousel">
            				<%if(memImgPath.size()>1){ %>
           						 <a class="prev" ></a>
           				     <%} %> 
            				<ul>
           					  <%
		       					for(String mpath:memImgPath){
             					%>	
              				  <li><i></i><img src="<%=mpath %>" alt="Image" ></li>
             				<%} %>	
            			    </ul>
            				<%if(memImgPath.size()>1){ %>
           						 <a class="next" ></a>
            				<%} %> 
             				</div>
            				 <%} %>
                     	 </div>
                     	 <div class="commentBox">
                     	   <%
                     	      String href="/sview/entity/o"+uriID+"?lang="+lang;
                     	      String title = memname;
                     	   %>
                     	   <div class="entity-memname"><a target="_blank" href="<%=href %>" title="<%=title%>" class='mem-entity-label'><%=memname %></a></div>
                     	  <%
                            if(memTypeMap.keySet().size()>0){
                          %>
                          <div class="entity-type">
                            is a <span class="type" >
                           <%
                               int c = 0;  
                               for(Integer type_id:memTypeMap.keySet()){
                	           c++;
                	           if(c>=11){
                            %>
                           <span>...</span> 
                           <%
                            break;
                	       }
                	       String type_label = memTypeMap.get(type_id) ;
                	      if(type_label!=null&&!type_label.trim().equals("")){
                          %>
                          <span type_id=<%=type_id %>><%=type_label %></span>
                          <%
                	     }else{
                	     if(!lang.equals("en")){
            		   	   try{
            		   	     type_label = URILabelCache.getInstance().getLabel(new Integer(type_id),"en");
            		   		 if(type_label.equals(""))
            		   		   type_label = URIUtil.getLocalname(URIIDCache.getInstance().getURI(type_id)) ;
            		   	   }catch(Throwable e){
            		   		   e.printStackTrace();
            		   	   }
            		   	  }
                	     if(type_label.equals("")){
           	 	   		   if(lang.equals("en"))
           	 	   		     type_label ="Type"+type_id;
           	 	   		 else if(lang.equals("zh"))
           	 	   			type_label="类型"+type_id;
           	 	   	     }
                        %>
                           <span class="vacant" type_id=<%=type_id %>><%=type_label %></span>  
                        <%
                	   }
                	   if(c<memTypeMap.keySet().size()){
                       %>
                        ,
                       <%
                	       }
                          }
                        %>
                      </span>
                       </div>
                       <%} %>
                     	</div>
                     	<div style="clear:both"></div>
                     </div>
                 </li>
              <%}%>
               </ul>
             </div>
             <div class="filterBox">
                <div class='filter-title'>Filter this collection
                </div>
                <div class="filter-content">
                  <div class="myac-box qitem-box-inmem left">
                     <span class="myac-ophint">Add a filter</span> <input class="myac-input qitem"  type="text"  />
	               </div>
	               <ul class="filterList">
	               </ul>
                </div>
             </div>
         </div>
         <div class="tab-pane" id="view-content">
            <div class="subtab">
                <ul class="nav nav-pills mypill">
                   <li class="tableview" refresh="0"><a href="#tableView">table</a> </li>
                   <li class="listview" refresh="0"><a href="#listView">list</a></li>
                 </ul>
            </div>
            <div class="tab-content">
              <div  class="view-tab-content tab-pane" id ="tableView">
              	  <div class="myac-box qitem-box-inview">
                    <span class="myac-ophint">Add a query item</span><input class="myac-input qitem" type="text" />
	              </div>
                  <div class="flexigrid"><div class="vcontent" ></div></div>
              </div>
              <div  class="view-tab-content tab-pane" id ="listView">
	              <div class="myac-box qitem-box-inview">
                    <span class="myac-ophint">Add a query item</span><input class="myac-input qitem" type="text" />
	              </div>
                  <div class="vcontent" ></div>
               </div>   
          </div>                    
         </div>
      </div>
  </div>
 </div>
  <div class='recommend-container'>
  	<div class="recommend-box"></div>
  </div>  
</div>
<jsp:include page="/vfooter.jsp"></jsp:include>
<%
 EntityManagement.storeUserVisit(user,entityType,entityId,lang); %>
<input type='hidden' name="display-lang" id="display-lang" value="en"/>
<input type='hidden'  id="etype" value=<%=etype %> />
<input type='hidden'  id="eid" value=<%=entityId %> />
<input type="hidden" id="genre" value=<%=genre%> />
<input type="hidden" id="groupID" value=<%=groupID%> />
<input type='hidden'  id="count" value="0" />
<div class="collectionMembers hidden">
   <div class='origin'>
   </div>
</div>
<div class="hidden">
  <div id="bookmark-op" title="Bookmark" class="section">
  	 <div class="fields">
        <label>Name</label>
        <input class='ftext itext' type="text" name="name" value="<%=name %>" id="bookmarkName"/>
        <div class="errorMsg"></div>
     </div>  
  </div>
  <div id="warning-op" title="Warning">
        The bookmark name has existed! 
        <ul>
           <li class="bmwarn_op ov"><a href="javascript:void(0)">Overwrite it.</a></li>
           <li class="bmwarn_op cancel"><a href="javascript:void(0)">Discard last bookmark operation.</a></li>
        </ul>
  </div>
  <div class='fdialog'></div>
</div>
</body>
</html>